package top.xana.acg.anime.utils

import com.google.gson.Gson
import com.google.gson.JsonElement
import java.lang.reflect.Type

object GsonUtils {

    val gson = Gson()

    inline fun <reified T> safeParseJson(json: String?): T? = try {
        gson.fromJson(json, T::class.java)
    } catch (e: Exception) {
        LogE("Error occurred when safe parse json. String:$json", t = e)
        e.printStackTrace()
        null
    }

    inline fun <reified T> safeParseJson(jsonElement: JsonElement?): T? = try {
        gson.fromJson(jsonElement, T::class.java)
    } catch (e: Exception) {
        LogE("Error occurred when safe parse json.", t = e)
        e.printStackTrace()
        null
    }

    fun <T> safeParseJson(json: String?, type: Type): T? = try {
        gson.fromJson<T>(json, type)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }

    fun <T> safeParseJson(jsonElement: JsonElement?, type: Type): T? = try {
        gson.fromJson<T>(jsonElement, type)
    } catch (e: Exception) {
        LogE("Error occurred when safe parse json.", t = e)
        e.printStackTrace()
        null
    }

/*    fun fromJson(json: String?): JsonElement? = try {
        JsonParser.parseString(json)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }*/

    @JvmStatic
    fun toJson(any: Any): String? = try {
        gson.toJson(any)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }


}